package com.imooc.network;

import org.junit.Test;

import java.io.*;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;

/**
 * @Date:2021/10/19/20:31
 * @Description:
 */
public class TCPTest01 {

    @Test
    public void client()  {



        Socket socket =null;

        OutputStream os=null;

        try{
            //1.创建Socker 对象，指明服务器端的ip和端口号
            InetAddress inet = InetAddress.getByName("localhost");
            socket = new Socket(inet,8899);  // 2021/10/19 实现端点

            //2 获取一个输出流，用于输入数据
            os = socket.getOutputStream();
            os.write("你好，我是客户端MM".getBytes());
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if(os !=null){
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(socket != null){
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }

    }

    @Test
    public void server() {

        ServerSocket ss=null;
        Socket socket=null;
        InputStream is=null;
        ByteArrayOutputStream baos=null;

        try{
            //1 创建服务器的 ServerSocket，指明自己的端口号
            ss = new ServerSocket(8899);
            //2 调用accept()表示接受来自客户端的数据
             socket = ss.accept();

             //3 获取输入流
             is = socket.getInputStream();

             //4 读取流数据
             baos = new ByteArrayOutputStream(); // 有一个数组 protected byte buf[]，可以一直往里面填数据
            byte[] buffer = new byte[5];
            int len;
            while ((len =is.read(buffer) )!= -1){
                baos.write(buffer,0,len);
            }

            System.out.println(baos.toString());

        }catch (Exception e){
            e.printStackTrace();
        }finally {   //关闭资源
            if(baos != null){
                try {
                    baos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(is !=null){
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(socket !=null){
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(ss !=null){
                try {
                    ss.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }









    }


}
